import "./index.scss";
import { useState, useEffect } from "react";
import {
  Button,
  Select,
  Form,
  Input,
  DatePicker,
  Table,
  Modal,
  Space,
  message,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import { useNavigate } from "react-router-dom";
import http from "../../../utils/http";
import "dayjs/locale/zh-cn";
import locale from "antd/es/date-picker/locale/zh_CN";

const StudentFiling = () => {
  //时间转换
  const toDub = (n: any) => (n < 10 ? "0" + n : "" + n);
  //年月日时分秒
  const toTime = (date: any) => {
    const oTime = new Date(date);
    return (
      oTime.getFullYear() +
      "-" +
      toDub(oTime.getMonth() + 1) +
      "-" +
      toDub(oTime.getDate()) +
      " " +
      toDub(oTime.getHours()) +
      ":" +
      toDub(oTime.getMinutes()) +
      ":" +
      toDub(oTime.getSeconds())
    );
  };
  //年月日
  const toDate = (date: any) => {
    const oDate = new Date(date);
    return (
      oDate.getFullYear() +
      "-" +
      toDub(oDate.getMonth() + 1) +
      "-" +
      toDub(oDate.getDate())
    );
  };

  //获取所有机构
  const [ins, useins] = useState([]);
  const getIns = () => {
    http({
      url: "/getIns",
    }).then((res) => {
      console.log("-------", res.data);

      let ins = res.data.map((v: { oname: any }) => {
        return v;
      });
      console.log("insinsins", ins);
      useins(ins);
    });
  };
  useEffect(() => {
    getIns();
  }, []);

  //渲染数据
  const getData = () => {
    http({
      url: "/getStudent",
    }).then((res) => {
      console.log("所有数据", res);
      let _data = res.data.map((v: { id: number }) => {
        return { ...v, key: v.id };
      });
      setData(_data);
    });
  };
  useEffect(() => {
    getData();
  }, []);

  //搜索
  const onSearch = (search: any) => {
    console.log("search", JSON.stringify(search));
    http({
      url: "/searchStudent",
      params: {
        sname: search.sname || "",
        sidentity: search.sidentity || "",
        ssex: search.ssex || "",
        sparents: search.sparents || "",
        sinstitution: search.sinstitution || "",
        scourse: search.scourse || "",
        stime:
          toDate(search.stime) == "NaN-NaN-NaN"
            ? ""
            : toDate(search.stime) || "",
        sborn:
          toDate(search.sborn) == "NaN-NaN-NaN"
            ? ""
            : toDate(search.sborn) || "",
      },
    }).then((res: { [key: string]: any }) => {
      console.log(res);
      if (res.error == 0) {
        message.success("查询成功");
        let _data = res.data.map((v: { id: number }) => {
          return { ...v, key: v.id };
        });
        setData(_data);
      } else {
        message.error("查询失败");
      }
    });
  };

  //清空搜索
  const [searchText] = Form.useForm();
  const clear = () => {
    searchText.resetFields();
    getData();
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };

  //接口
  interface DataType {
    key: string;
    sname: string;
    scourse: string;
    sinstitution: string;
    ssex: string;
    sborn: string;
    sidentity: string;
    sarea: string;
    sparents: string;
    stime: string;
  }

  //表格姓名跳转
  const navigate = useNavigate();
  const toDetail = (record: any) => {
    console.log("record", record);
    navigate(`/zhome/z-studentDetail`, { state: record });
  };

  //表格
  const columns: ColumnsType<DataType> = [
    {
      title: "姓名",
      dataIndex: "sname",
      key: "sname",
      render: (text, record) => (
        <a
          onClick={() => {
            toDetail(record);
          }}
          className="edit"
        >
          {text}
        </a>
      ),
    },
    {
      title: "培训课程",
      dataIndex: "scourse",
      key: "scourse",
    },
    {
      title: "培训机构",
      dataIndex: "sinstitution",
      key: "sinstitution",
    },
    {
      title: "性别",
      dataIndex: "ssex",
      key: "ssex",
    },
    {
      title: "出生年月",
      dataIndex: "sborn",
      key: "sborn",
      render: (text) => <a className="todate">{toDate(text)}</a>,
    },
    {
      title: "身份证号码",
      dataIndex: "sidentity",
      key: "sidentity",
    },
    {
      title: "家长电话",
      dataIndex: "sparents",
      key: "sparents",
    },
    {
      title: "备案时间",
      dataIndex: "stime",
      key: "stime",
      render: (text) => <a className="todate">{toTime(text)}</a>,
    },
    {
      title: "操作",
      key: "action",
      render: (_: any, record: any) => (
        <Space size="middle">
          <a
            onClick={() => {
              showEdit(record);
            }}
            className="edit"
          >
            编辑
          </a>
        </Space>
      ),
    },
  ];
  const [data, setData] = useState([]);

  // 编辑框
  const [editForm] = Form.useForm();
  const [isModalOpen, setIsEditOpen] = useState(false);

  const showEdit = (record: any) => {
    console.log("editrecord", record);
    editForm.setFieldsValue({ ...record });
    setIsEditOpen(true);
  };
  // 确定编辑
  const handleOk = () => {
    const data = editForm.getFieldsValue(true);
    http({
      url: "/editStudent",
      method: "post",
      data: data,
    }).then((res: { [key: string]: any }) => {
      console.log(res);
      if (res.error == 0) {
        message.success("修改成功");
        setIsEditOpen(false);
        getData();
      } else {
        message.error("修改失败");
      }
    });
    setIsEditOpen(false);
  };
  const handleCancel = () => {
    setIsEditOpen(false);
  };

  // 新增
  const [isAddOpen, setIsAddOpen] = useState(false);
  const showAdd = () => {
    setIsAddOpen(true);
  };
  // 确定新增
  const [addText] = Form.useForm();
  const onAdd = (values: any) => {
    console.log("Add:", values);
    http({
      url: "/addStudent",
      method: "post",
      data: {
        sname: values.sname,
        sinstitution: values.sinstitution,
        sborn: toDate(values.sborn),
        ssex: values.ssex,
        sidentity: values.sidentity,
        sparents: values.sparents,
        scourse: values.scourse,
        sgrade: values.sgrade,
        sschool: values.sschool,
      },
    }).then((res: { [key: string]: any }) => {
      console.log(res);
      if (res.error == 0) {
        message.success("添加成功");
        setIsAddOpen(false);
        addText.resetFields();
        getData();
      } else {
        message.error("添加失败");
      }
    });
  };
  const handleCancelAdd = () => {
    setIsAddOpen(false);
  };

  return (
    <div className="student-filing">
      <div className="title">学生备案</div>

      <div className="hr"></div>

      <Form
        name="basic"
        form={searchText}
        initialValues={{ remember: true }}
        onFinish={onSearch}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
        className="form"
      >
        <Form.Item label="学生姓名" name="sname" style={{ width: 200 }}>
          <Input />
        </Form.Item>

        <Form.Item label="所属机构" name="sinstitution" className="institution">
          <Select allowClear={true}>
            {ins.map((i: any) => (
              <Select.Option value={i.oname}>{i.oname}</Select.Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item label="性别" className="sex" name="ssex">
          <Select>
            <Select.Option value="男">男</Select.Option>
            <Select.Option value="女">女</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item label="身份证号码" name="sidentity" className="identity">
          <Input />
        </Form.Item>

        <Form.Item label="家长电话" name="sparents" className="parents">
          <Input />
        </Form.Item>

        <Form.Item label="出生年月" name="sborn" className="born">
          <DatePicker locale={locale} placeholder="" />
        </Form.Item>

        <Form.Item label="培训学科" name="scourse" className="subject">
          <Select>
            <Select.Option value="数学">数学</Select.Option>
            <Select.Option value="语文">语文</Select.Option>
            <Select.Option value="英语">英语</Select.Option>
            <Select.Option value="物理">物理</Select.Option>
            <Select.Option value="化学">化学</Select.Option>
            <Select.Option value="地理">地理</Select.Option>
            <Select.Option value="生物">生物</Select.Option>
            <Select.Option value="政治">政治</Select.Option>
            <Select.Option value="历史">历史</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item label="备案时间" name="stime" className="time">
          <DatePicker locale={locale} placeholder="" />
        </Form.Item>

        <Form.Item>
          <Button className="btn1" htmlType="submit">
            查询
          </Button>
        </Form.Item>

        <Form.Item>
          <Button className="btn" onClick={clear}>
            清空查询
          </Button>
        </Form.Item>

        <Form.Item>
          <Button className="btn" onClick={showAdd}>
            新增
          </Button>
        </Form.Item>
      </Form>

      <Table
        className="table"
        pagination={{ defaultPageSize: 5 }}
        columns={columns}
        dataSource={data}
      />

      {/* 编辑框 */}
      <Modal
        title="编辑"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        okText={"确认"}
        cancelText={"取消"}
      >
        <Form
          form={editForm}
          name="basic"
          initialValues={{ remember: true }}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 16 }}
          autoComplete="off"
        >
          <Form.Item
            label="学生姓名"
            name="sname"
            rules={[
              {
                required: true,
                pattern: /^[\u2E80-\u9FFF]+$/,
                message: "请输入学生姓名!",
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="所属机构"
            rules={[{ required: true, message: "请选择所属机构!" }]}
            name="sinstitution"
          >
            <Select allowClear={true}>
              {ins.map((i: any) => (
                <Select.Option value={i.oname}>{i.oname}</Select.Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            label="性别"
            name="ssex"
            rules={[{ required: true, message: "请选择学生性别!" }]}
          >
            <Select>
              <Select.Option value="男">男</Select.Option>
              <Select.Option value="女">女</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item
            label="身份证号码"
            rules={[
              {
                required: true,
                pattern:
                  /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/,
                message: "请输入学生正确身份证号!",
              },
            ]}
            name="sidentity"
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="家长电话"
            rules={[
              {
                required: true,
                pattern: /^1[3456789]\d{9}$/,
                message: "请输入正确的家长电话!",
              },
            ]}
            name="sparents"
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="培训学科"
            rules={[{ required: true, message: "请选择培训学科!" }]}
            name="scourse"
          >
            <Select>
              <Select.Option value="数学">数学</Select.Option>
              <Select.Option value="语文">语文</Select.Option>
              <Select.Option value="英语">英语</Select.Option>
              <Select.Option value="物理">物理</Select.Option>
              <Select.Option value="化学">化学</Select.Option>
              <Select.Option value="地理">地理</Select.Option>
              <Select.Option value="生物">生物</Select.Option>
              <Select.Option value="政治">政治</Select.Option>
              <Select.Option value="历史">历史</Select.Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      {/* 新增框 */}
      <Modal
        title="新增"
        open={isAddOpen}
        onCancel={handleCancelAdd}
        footer={null}
      >
        <Form
          form={addText}
          name="basic"
          initialValues={{ remember: true }}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 16 }}
          autoComplete="off"
          onFinish={onAdd}
        >
          <div className="items">
            <Form.Item
              label="学生姓名"
              name="sname"
              style={{ width: 300 }}
              rules={[
                {
                  required: true,
                  pattern: /^[\u2E80-\u9FFF]+$/,
                  message: "请输入学生姓名!",
                },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="所属机构"
              style={{ width: 300 }}
              name="sinstitution"
              rules={[{ required: true, message: "请选择所属机构!" }]}
            >
              <Select allowClear={true}>
                {ins.map((i: any) => (
                  <Select.Option value={i.oname}>{i.oname}</Select.Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              label="出生年月"
              name="sborn"
              style={{ width: 300 }}
              rules={[{ required: true, message: "请选择出生年月!" }]}
            >
              <DatePicker locale={locale} placeholder="" />
            </Form.Item>

            <Form.Item
              label="性别"
              style={{ width: 300 }}
              rules={[{ required: true, message: "请选择学生性别!" }]}
              name="ssex"
            >
              <Select>
                <Select.Option value="男">男</Select.Option>
                <Select.Option value="女">女</Select.Option>
              </Select>
            </Form.Item>

            <Form.Item
              label="身份证号"
              style={{ width: 300 }}
              rules={[
                {
                  required: true,
                  pattern:
                    /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/,
                  message: "请输入学生正确身份证号!",
                },
              ]}
              name="sidentity"
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="家长电话"
              style={{ width: 300 }}
              rules={[
                {
                  required: true,
                  pattern: /^1[3456789]\d{9}$/,
                  message: "请输入正确的家长电话!",
                },
              ]}
              name="sparents"
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="培训学科"
              style={{ width: 300 }}
              rules={[{ required: true, message: "请选择培训学科!" }]}
              name="scourse"
            >
              <Select>
                <Select.Option value="数学">数学</Select.Option>
                <Select.Option value="语文">语文</Select.Option>
                <Select.Option value="英语">英语</Select.Option>
                <Select.Option value="物理">物理</Select.Option>
                <Select.Option value="化学">化学</Select.Option>
                <Select.Option value="地理">地理</Select.Option>
                <Select.Option value="生物">生物</Select.Option>
                <Select.Option value="政治">政治</Select.Option>
                <Select.Option value="历史">历史</Select.Option>
              </Select>
            </Form.Item>

            <Form.Item
              label="在读年级"
              style={{ width: 300 }}
              rules={[{ required: true, message: "请输入在读年级!" }]}
              name="sgrade"
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="在读学校"
              style={{ width: 300 }}
              rules={[{ required: true, message: "请输入在读学校!" }]}
              name="sschool"
            >
              <Input />
            </Form.Item>
          </div>

          <Form.Item wrapperCol={{ offset: 16, span: 16 }}>
            <Button
              className="clear"
              htmlType="button"
              onClick={handleCancelAdd}
            >
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              确定
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default StudentFiling;
